//yw 1初始化
layui.use(['form', 'layer', 'table'], function () {
    var $ = layui.jquery;
    var form = layui.form;
    var table = layui.table;
    var layer = layui.layer;
    var navList = null;//所有学校数据
    var schoolid = null;

    //获取所有学校名
    if(navList == null){
        $.ajax({ //yw 从后台获取学校数据，填充前端的学校下拉框
            url:'/school/queryAllSchool?page=1&pageSize=10',
            dataType:'json',
            async:false,
            type:'post',
            success:function(data){
                //alert(data.data[0].schoolname);
                navList = data.data;
                navRender(navList);
            }
        })
    }else{
        navRender(navList);
    }
    //填充左侧导航栏
    function navRender(navList){
        var navData = '';
        for(var i = 0;i<navList.length;i++){
            navData += "<li class='nav-item'><a href='javascript:;'><input hidden='hidden' value='"+navList[i].schoolid +"'/><span>"+navList[i].schoolname+"</span></a></li>"
        }
        // console.log(navData)
        $('#aat').html(navData);
        schoolid = navList[0].schoolid;//设置学校id默认值
    }
    //xqr 2显示表格数据
    var tableIns = table.render({
        elem: '#buildlist',
        url: '/build/queryAllBuild', //数据接口
        cellMinWidth: 95,
        page: true, //开启分页
        height: 500,
        width: 750,
        limits: [10, 15, 20, 25],
        limit: 10,
        method: 'post',
        cols: [[ //表头
            {field: 'schoolid', title: '学校'},
            {field: 'tbuildname', title: '教学楼名称'},
            {field: 'tbuildid', title: '教学楼ID'},
            {field: 'addtime',minwidth: 150,width: 180,title: '添加时间', sort: true},
            {title: '操作', minWidth: 120, width: 150, toolbar: '#listRowBar', fixed: "right", align: "center"}
        ]],
        request: {
            pageName: 'page' //页码的参数名称，默认：page
            , limitName: 'pageSize' //每页数据量的参数名，默认：limit
        },
        where:{schoolid:schoolid}
    });
    //xqr 获取左侧导航栏学校id,重新渲染表格数据
    $(".nav ul li").on("click",function(){
        schoolid = $(this).find("input").val(); //使用this获取input的值
        //alert(schoolid);
        //xqr 重新导入表格数据
        tableIns.reload({
            page:{
                curr: 1
            },
            where:{
                schoolid: schoolid
            },
            url:'/build/queryAllBuild'
        });
    });

    //禁止表单回车提交
    $('form').on('keydown', function (event) {
        if (event.keyCode == 13) return false;
    })

    //搜索按钮
    $("#search_btn").on("click",function(){
        tableIns.reload({
            page:{
                curr: 1
            },
            where:{
                //接口对应的参数值的名称
                tbuildname: $(".searchVal").val(),
                schoolid:schoolid
            },
            url:'/build/queryAllBuild'
        });
        //alert($(".searchVal").val());
    });
    //打开添加的弹出窗
    $("#add_btn").on("click",function(){
        layer.open({
            title: ['添加教学楼', 'font-size:18px;text-align:center;color:blue;'],
            type: 1,
            content: $("#addDiv"),
            area: ['400px', '280px'],
            offset: 'auto',
            success: function (layero, index) { //yw layero是弹出层对象layer object
                // $("#schoolnameId").val(data.schoolid);
                // $("#tbuildnameId").val(data.tbuildname);
                $("#schoolname2").empty();
                $.each(navList,function(index,item){
                    $("#schoolname2").append(new Option(item.schoolname,item.schoolid));
                });
                form.render("select");
            }
        })
    });
    //xqr 根据点击的学校填充部分教学楼ID
    form.on("select(schoolname2)",function(){
        $("#tbuildId2").val($("#schoolname2").val());
    });
    // 操作 添加教学楼
    form.on("submit(doSubmitAdd)", function () {
        //获取到文本域中的文字
        var schoolid = $("#schoolname2").val();
        var tbuildname = $("#tbuildnameId2").val();
        var tbuildid = $("#tbuildId2").val();
        // alert(schoolid);
        // alert(tbuildname);
        // alert(tbuildid);
        $.ajax({
            type: "post",
            url: "/build/addBuild",
            data: {tbuildname: tbuildname,tbuildid: tbuildid,schoolid:schoolid},
            success: function (res) {
                if (res == 1) {
                    tableIns.reload();
                    layer.msg('添加成功', {icon: 7, time: 800, shade: [0.6, '#000', true]});
                    layer.closeAll('page'); // 关闭添加界面 type=1
                }else if(res == 2) {
                    layer.msg('教学楼id重复，请更换！', {icon: 7, time: 800, shade: [0.6, '#000', true]});
                }else if(res == 3) {
                    layer.msg('教学楼id有误，前三位应为学校id!', {icon: 7, time: 800, shade: [0.6, '#000', true]});
                } else {
                    layer.msg('添加失败', {icon: 7, time: 800, shade: [0.6, '#000', true]});
                }
            }
        });
    });
    //监听行工具条的事件(表格操作)
    table.on("tool(buildlist)", function (obj) {
        var data = obj.data; //获得当前行数据
        switch (obj.event) {
            case 'edit':
                openUpdateLayer(data);
                break;
            case 'del':
                deleteInfo(data);
                break;
        }
    });

    // 3操作 3)更新  (a)打开修改的弹出层
    function openUpdateLayer(data) {
        mainIndex = layer.open({
            title: ['修改教学楼', 'font-size:18px;text-align:center;color:blue;'],
            type: 1,
            content: $("#editDiv"),
            area: ['400px', '240px'],
            offset: 'auto',
            success: function (layero, index) { //yw layero是弹出层对象layer object
                $("#tbuildid").val(data.tbuildid);
                $("#schoolnameId").val(data.schoolid);
                $("#tbuildnameId").val(data.tbuildname);
            }
        });
    }

    //xqr 3操作 3)更新 (b)提交监听事件--修改记录
    form.on("submit(doSubmitSave)", function () {
        //获取到文本域中的文字
        var tbuildname = $("#tbuildnameId").val();
        var tbuildid = $("#tbuildid").val();
        //alert(tbuildname);
        //alert(tbuildid);
        $.ajax({
            type: "post",
            url: "/build/saveBuild",
            data: {tbuildname: tbuildname,tbuildid: tbuildid},
            success: function (res) {
                if (res) {
                    tableIns.reload();
                    layer.msg('保存成功', {icon: 7, time: 800, shade: [0.6, '#000', true]});
                } else {
                    layer.msg('保存失败', {icon: 7, time: 800, shade: [0.6, '#000', true]});
                }
                layer.closeAll('page'); // 关闭编辑界面 type=1
            }
        });
    });

    // 3操作 4)删除
    function deleteInfo(data) {
        layer.confirm('你确定要删除 \'' + data.schoolid + '\' 里的 \'' + data.tbuildname + '\' 吗?', {
            icon: 3,
            title: '提示'
        }, function (index) {
            $.ajax({
                type: "post",
                url: '/build/delBuild?tbuildid=' + data.tbuildid,
                success: function (res) {
                    if (res) {
                        tableIns.reload();
                        layer.msg('删除成功', {icon: 7, time: 800, shade: [0.6, '#000', true]});
                    } else {
                        layer.msg('删除失败', {icon: 7, time: 800, shade: [0.6, '#000', true]});
                    }
                }
            });
            layer.close(index); //yw 关闭删除提示对话框
            tableIns.reload();
        });
    }

    //yw 4表单验证
    form.verify({
        required: [/[\S]+/, "不能为空"],
        username: [/^[a-zA-Z0-9_-]{4,16}$/, "用户名4-16位字母数字下划线减号"],
        phone: [/(^$)|^1\d{10}$/, "请输入正确的手机号"],
        email: [/(^$)|^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/, "邮箱格式不正确"],
        url: [/(^$)|(^#)|(^http(s*):\/\/[^\s]+\.[^\s]+)/, "链接格式不正确"],
        integer: [/^\d*$/, "只能填写整数"],
        date: [/(^$)|^(\d{4})[-\/](\d{1}|0\d{1}|1[0-2])([-\/](\d{1}|0\d{1}|[1-2][0-9]|3[0-1]))*$/, "日期格式不正确"],
        identity: [/(^$)|(^\d{15}$)|(^\d{17}(x|X|\d)$)/, "请输入正确的身份证号"],
        // 校验两次密码是否一致
        userPwd: [/(.+){6,12}$/, '密码必须6到12位'],
        userPwdCheck: function (value) {
            if ($('input[name=userPwd]').val() !== value)
                return '两次密码输入不一致！';
        },
        number: function (e) {
            if (e && isNaN(e)) return "只能填写数字"
        },
        lenLimit10: function (value) {
            if (value.length > 10) return '长度不能超过10个字符';
        },
        lenLimit20: function (value) {
            if (value.length > 20) return '长度不能超过20个字符';
        },
        lenLimit50: function (value) {
            if (value.length > 20) return '长度不能超过50个字符';
        },
        lenLimit100: function (value) {
            if (value.length > 100) return '长度不能超过50个字符';
        }
    });
});//yw 最后一行对应layui.use(['form','layer','laydate','table'],function(){
